"""
分块元数据模块

定义分块过程中的元数据结构和管理功能。
"""

from dataclasses import dataclass
from typing import List, Optional


@dataclass
class ChunkMetadata:
    """
    分块元数据

    存储分块的详细信息和层次关系，用于追踪和优化分块质量。

    Attributes:
        chunk_index: 分块在文档中的索引
        source_doc_id: 源文档ID
        chunk_size: 分块大小（字符数）
        semantic_score: 语义相关度得分（可选）
        chunk_type: 分块类型标识
        parent_chunk_id: 父级分块ID（层次分块使用）
        child_chunk_ids: 子级分块ID列表（层次分块使用）
    """
    chunk_index: int
    source_doc_id: str
    chunk_size: int
    semantic_score: Optional[float] = None
    chunk_type: str = "standard"
    parent_chunk_id: Optional[str] = None
    child_chunk_ids: Optional[List[str]] = None

    def __post_init__(self):
        """初始化后处理"""
        if self.child_chunk_ids is None:
            self.child_chunk_ids = []

    def add_child_chunk(self, child_id: str) -> None:
        """添加子级分块ID"""
        if self.child_chunk_ids is None:
            self.child_chunk_ids = []
        self.child_chunk_ids.append(child_id)

    def remove_child_chunk(self, child_id: str) -> None:
        """移除子级分块ID"""
        if self.child_chunk_ids and child_id in self.child_chunk_ids:
            self.child_chunk_ids.remove(child_id)

    def has_children(self) -> bool:
        """检查是否有子级分块"""
        return bool(self.child_chunk_ids)

    def has_parent(self) -> bool:
        """检查是否有父级分块"""
        return self.parent_chunk_id is not None

    def get_hierarchy_level(self) -> int:
        """获取层次级别（0=根级，1=子级，2=孙级...）"""
        level = 0
        # 在实际应用中，这需要通过查询完整的分块树来确定
        # 这里简化为基于是否有父子关系的判断
        if self.has_parent():
            level += 1
        if self.has_children():
            level += 1
        return level

    def to_dict(self) -> dict:
        """转换为字典格式"""
        return {
            "chunk_index": self.chunk_index,
            "source_doc_id": self.source_doc_id,
            "chunk_size": self.chunk_size,
            "semantic_score": self.semantic_score,
            "chunk_type": self.chunk_type,
            "parent_chunk_id": self.parent_chunk_id,
            "child_chunk_ids": self.child_chunk_ids,
            "hierarchy_level": self.get_hierarchy_level()
        }

    @classmethod
    def from_dict(cls, data: dict) -> 'ChunkMetadata':
        """从字典创建实例"""
        return cls(
            chunk_index=data["chunk_index"],
            source_doc_id=data["source_doc_id"],
            chunk_size=data["chunk_size"],
            semantic_score=data.get("semantic_score"),
            chunk_type=data.get("chunk_type", "standard"),
            parent_chunk_id=data.get("parent_chunk_id"),
            child_chunk_ids=data.get("child_chunk_ids")
        )

    def __str__(self) -> str:
        """返回字符串表示"""
        parent_info = f"父级: {self.parent_chunk_id}" if self.has_parent() else "无父级"
        children_info = f"子级数: {len(self.child_chunk_ids)}" if self.has_children() else "无子级"

        return (
            f"分块元数据 [索引: {self.chunk_index} | "
            f"大小: {self.chunk_size} | "
            f"类型: {self.chunk_type} | "
            f"{parent_info} | {children_info}]"
        )